//
//  UISwitchExtensions.swift
//  Fangxukanghan
//
//  Created by 常超群的MacBookPro on 2021/4/21.
//

import UIKit

public extension UISwitch {
    func ccq_tapHandler(_ closure: @escaping CCQVoidClosure) { ccq_addTarget { _ in closure() } }
    func ccq_addTarget(for event: UIControl.Event = .valueChanged, closure: @escaping (UISwitch) -> Void) {
        targetClosure = closure
        addTarget(self, action: #selector(UISwitch.closureAction), for: event)
    }
    private struct AssociatedKeys { static var targetClosure = "targetClosure" }
    private class ClosureWrapper: NSObject {
        let closure: (UISwitch) -> Void
        init(_ closure: @escaping (UISwitch) -> Void) { self.closure = closure }
    }
    @objc private func closureAction() { targetClosure?(self) }
    private var targetClosure: ((UISwitch) -> Void)? {
        get { return (objc_getAssociatedObject(self, &AssociatedKeys.targetClosure) as? ClosureWrapper)?.closure }
        set {
            guard let newValue = newValue else { return }
            objc_setAssociatedObject(self, &AssociatedKeys.targetClosure, ClosureWrapper(newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}
